import React, {useMemo, useRef} from 'react';
import {Button, Space, Table, Tabs, Modal, Descriptions, Input} from 'antd';
import '../../styles/card.scss';
import useDidMount from '../../hooks/useDidMount';
import useCheckInModel from './checkin_module';
import useGlobal from '../../hooks/useGlobal';
import PhotoPreview from '../../component/photoPreview';

const {TabPane} = Tabs;

const CheckIn = () => {

  const CheckInModel = useCheckInModel();
  const Global = useGlobal();
  const scoreRef = useRef();

  useDidMount(() => {

    // 初始化获取对应数据
    async function init() {
      if (Global.state.schoolList.length < 1) {
        await Global.effect.updateSchoolList();
      }
      if (Global.state.memberList.length < 1) {
        await Global.effect.updateMemberList();
      }
      // if (Global.state.checkInTypeList.length < 1) {
      //   await Global.effect.updateCheckInTypeList();
      // }
      await CheckInModel.effect.getCardList();
    }

    init();
  });

  const handleCheckDetail = (item) => {
    const modal = Modal.info({
      icon: null,
      width: 800,
      content: (
        <div>
          <Descriptions title="打卡详情" bordered column={1}>
            <Descriptions.Item label="学生姓名">{Global.effect.getMemberById(item.user_id).cname}</Descriptions.Item>
            <Descriptions.Item label="学校">{Global.effect.getSchoolById(item.school_id).name}</Descriptions.Item>
            <Descriptions.Item label="打卡类型">{Global.effect.getCheckInTypeById(item.type)}</Descriptions.Item>
            <Descriptions.Item label="活动名称">{item.name}</Descriptions.Item>
            <Descriptions.Item label="活动时间">{new Date(item.date * 1000).toLocaleDateString()}</Descriptions.Item>
            <Descriptions.Item label="活动心得">{item.context}</Descriptions.Item>
            <Descriptions.Item label="活动照片"><PhotoPreview list={item.photo.split(',')}/></Descriptions.Item>
            { item.status === 2 &&
              <Descriptions.Item label="审核">
                <Space>
                  <Button type="primary" onClick={() => {
                    Modal.confirm({
                      title: '请输入本次打卡可获得的积分',
                      content: <Input type="number" ref={scoreRef}/>,
                      onOk: async close => {
                        const score = scoreRef.current?.state.value || 0;
                        if (isNaN(score) || score <= 0) {
                          alert('请输入合法的数组：大于0的正整数');
                        }
                        await CheckInModel.effect.acceptCheckin(item.id, Math.floor(score));
                        close();
                        modal.destroy();
                      }
                    });
                  }}>通过</Button>
                  <Button danger onClick={() => {
                    Modal.confirm({
                      title: '打卡审核',
                      content: '是否确认不通过',
                      onOk: async close => {
                        await CheckInModel.effect.rejectCheckin(item.id);
                        close();
                        modal.destroy();
                      }
                    });
                  }}>不通过</Button>
                </Space>
              </Descriptions.Item>
            }
            {
              item.status === 1 &&
              <Descriptions.Item label="积分">{item.score}分</Descriptions.Item>
            }
          </Descriptions>
        </div>
      )
    });
  };

  const columns = useMemo(() => {
    // console.log(CheckInModel.state.unCheckedSchoolList);
    return [
      {
        title: '用户姓名',
        dataIndex: 'user_id',
        width: 200,
        render: id => Global.effect.getMemberById(id)?.cname
      },
      {
        title: '学校',
        dataIndex: 'school_id',
        width: 200,
        render: id => Global.effect.getSchoolById(id)?.name,
        filters: CheckInModel.state.schoolList
          .map(id => ({text: Global.effect.getSchoolById(id)?.name, value: id})),
        onFilter: (value, record) => record.school_id === value,
      },
      {
        title: '打卡类型',
        dataIndex: 'type',
        width: 200,
        render: type => Global.effect.getCheckInTypeById(type),
        filters: CheckInModel.state.typeList
          .map(type => ({text: Global.effect.getCheckInTypeById(type), value: type})),
        onFilter: (type, record) => record.type === type,
      },
      {
        title: '标题',
        dataIndex: 'name',
      },
      {
        title: '打卡时间',
        dataIndex: 'date',
        render: date => new Date(date * 1000).toLocaleDateString(),
        sorter: (a, b) => a.date - b.date,
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '操作',
        width: 200,
        render: (text, record) =>
          <Space size="middle">
            <Button onClick={e => handleCheckDetail(record, e)}>查看详情</Button>
          </Space>
      }
    ];
  }, [CheckInModel.state.schoolList, CheckInModel.state.typeList]);

  return (
    <div className={'checkin-list'}>
      <Tabs defaultActiveKey="1">
        <TabPane tab="待审核" key="1">
          <Table
            columns={columns}
            dataSource={CheckInModel.state.unCheckedList}
          />
        </TabPane>
        <TabPane tab="已审核" key="2">
          <Table
            columns={columns}
            dataSource={CheckInModel.state.checkedList}
          />
        </TabPane>
        <TabPane tab="已驳回" key="3">
          <Table
            columns={columns}
            dataSource={CheckInModel.state.rejectList}
          />
        </TabPane>
      </Tabs>
    </div>
  );
};

export default CheckIn;